package com.mp.db.jpa.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil 
{
    private static EntityManagerFactory factory = null;
    private static EntityManager manager = null;
    
       
    public static EntityManager getEntity()
    {
     
         if(factory == null || manager == null)
         {
             factory = Persistence.createEntityManagerFactory("MemoryPriceJPAPU");
             manager =  factory.createEntityManager();
         }  
     
         return manager;

    }
    
    public static void gravar(Object obj)
    {
        manager.getTransaction().begin();    
        manager.persist(obj);
        manager.getTransaction().commit();  
       
    }
    
    public static Object procurarPorId(Class c, int id)
    {
       return manager.find(c.getClass(),id);
    }
    
    public static void remover(Object obj,int id)
    {
        
        Object objRetorno = procurarPorId(obj.getClass(), id);

        manager.getTransaction().begin();
        manager.remove(objRetorno);
        manager.getTransaction().commit();
      
    }
    
     public static void merge(Object obj)
    {
        
       manager.getTransaction().begin();
       manager.merge(obj);
       manager.getTransaction().commit();
     
    }
    
    
    public static void closeEntity()
    {
        manager.close();
        factory.close();
    
    }
    
}
